package com.lagou.wwyan.rpc.server;

import com.lagou.wwyan.rpc.bean.RpcRequest;
import com.lagou.wwyan.rpc.bean.RpcResponse;
import com.lagou.wwyan.rpc.register.RpcRegister;
import com.lagou.wwyan.rpc.register.RpcRegisterFactory;
import com.lagou.wwyan.rpc.server.factory.RpcBeanFactory;
import com.lagou.wwyan.rpc.server.handler.RpcServerHandler;
import com.lagou.wwyan.rpc.service.UserService;
import com.lagou.wwyan.rpc.sirealizer.JSONSerializer;
import com.lagou.wwyan.rpc.sirealizer.RpcDecoder;
import com.lagou.wwyan.rpc.sirealizer.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class RpcServer {
    private RpcBeanFactory beanFactory;
    private RpcRegisterFactory registerFactory;
    private RpcRegister register;

    public RpcServer(RpcBeanFactory beanFactory, RpcRegisterFactory registerFactory) {
        this.beanFactory = beanFactory;
        this.registerFactory = registerFactory;
    }

    public void startServer(String host, int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        JSONSerializer serializer = new JSONSerializer();
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, serializer));
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, serializer));
                        pipeline.addLast(new RpcServerHandler(beanFactory));
                    }
                });

        ChannelFuture sync = bootstrap.bind(port).sync();

        //注册服务,todo 改为动态获取
        register = registerFactory.getRegister();
        register.registry(UserService.class.getName(),host,port);

        sync.channel().closeFuture().sync();
    }
}
